package tazadum.engine.ui;

import java.awt.DisplayMode;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;

import javax.swing.JFrame;

public class OpenGLFrame extends JFrame {
	private static final long serialVersionUID = 1L;

	private DisplayMode oldDisplayMode;

	public OpenGLFrame(final String title, final int width, final int height) {
		super(title);
		setSize(width, height);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	}

	public void setFullscreen() {
		final GraphicsEnvironment graphicsEnvironment = GraphicsEnvironment.getLocalGraphicsEnvironment();
		final GraphicsDevice screenDevice = getDevice(graphicsEnvironment);
		// for (final GraphicsConfiguration config : screenDevice.getConfigurations()) {
		// System.out.println(config.getBounds().toString());
		// }

		if (!screenDevice.isFullScreenSupported()) {
			System.err.println("Fullscreen is not supported");
		}

		oldDisplayMode = screenDevice.getDisplayMode();
		setUndecorated(true);
		setIgnoreRepaint(true);

		try {
			screenDevice.setFullScreenWindow(this);
		} catch (final Exception e) {
			screenDevice.setFullScreenWindow(null);
		}
	}

	private GraphicsDevice getDevice(final GraphicsEnvironment graphicsEnvironment) {
		int index = Integer.parseInt(System.getProperty("screen", "0"));
		final GraphicsDevice[] devices = graphicsEnvironment.getScreenDevices();
		if (index >= devices.length) {
			System.err.println("No such screen");
			index = 0;
		}
		return devices[index];
	}

	public void shutdown() {
		if (oldDisplayMode != null) {
			final GraphicsEnvironment graphicsEnvironment = GraphicsEnvironment.getLocalGraphicsEnvironment();
			final GraphicsDevice screenDevice = graphicsEnvironment.getDefaultScreenDevice();
			screenDevice.setFullScreenWindow(null);
			// screenDevice.setDisplayMode(oldDisplayMode);
			oldDisplayMode = null;
		}
	}

}
